package com.icepeach.icepeachhomeback.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.icepeach.icepeachhomeback.entity.User;
import com.icepeach.icepeachhomeback.exception.ServiceException;
import com.icepeach.icepeachhomeback.service.UserService;
import com.icepeach.icepeachhomeback.util.ApiResult;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    UserService userService;

    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        String uri = httpServletRequest.getRequestURI(); // 获取请求的URI
        // 如果请求的路径为 /file/upload，直接通过
        if (uri.endsWith("/file/upload")) {
            return true;
        }
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(ApiResult.CODE_UNAUTHORIZED, "为传入token");

        }
        // 获取 token 中的 user id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new ServiceException(ApiResult.CODE_UNAUTHORIZED, j.getMessage());
        }
        User user = userService.getById(userId);

        if (user == null) {
            throw new ServiceException(ApiResult.CODE_UNAUTHORIZED, "用户不存在");
        }
// 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException(ApiResult.CODE_UNAUTHORIZED, e.getMessage());
        }

        return true;
    }
}
